package com.juzhencms.apps.busi.web;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.juzhencms.apps.base.common.config.Config;
import com.juzhencms.apps.base.common.database.DBTable;
import com.juzhencms.apps.base.common.util.FileUtil;
import com.juzhencms.apps.base.common.util.WebUtil;
import com.juzhencms.apps.busi.service.CommonService;
import com.juzhencms.apps.busi.service.TemplateService;

import lombok.extern.slf4j.Slf4j;


@Controller
@RequestMapping("/template")
@Slf4j
public class TemplateController  extends BaseController{
	
	@Autowired
	private TemplateService templateService;
	
	@RequestMapping(value="/gridlistData",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String gridlistData(HttpServletRequest request){
		Map data=new HashMap();
		List whereParamList=new ArrayList();
		//显示所有未删除且状态正常的模板
		String where="where del_flag=0 and status=1 ";
		//用于站点管理中为站点选择模板，查询公共模板及独立模板，不需要显示复制模板
		if(request.getParameter("action")!=null && request.getParameter("action").toString().trim().equals("select_site_template")) {
			where+=" and template_type in(1,3) and site_id=0 ";
			/*//查询出所有绑定了站点的独立模板
			List usedTemplateList=this.getCommonService().getJdbcDao().querySql("select template_code from "+DBTable.site+" where del_flag=0 and template_type=3 and template_code is not null and template_code!=''");
			if(usedTemplateList!=null && usedTemplateList.size()>0) {
				List tmpArr=new ArrayList();
				for(int i=0;i<usedTemplateList.size();i++) {
					Map row=(Map)usedTemplateList.get(i);
					tmpArr.add("'"+row.get("template_code")+"'");
				}
				where+=" and code not in("+org.apache.commons.lang3.StringUtils.join(tmpArr, ",")+") ";
			}*/
		}
		
		
		//搜索参数
		if(request.getParameter("name")!=null && !request.getParameter("name").toString().trim().equals("")){
			where+=" and name like ? ";
			whereParamList.add("%"+request.getParameter("name")+"%");
		}
		
		if(request.getParameter("publish")!=null && !request.getParameter("publish").toString().trim().equals("")){
			where+=" and publish = ? ";
			whereParamList.add(request.getParameter("publish"));
		}
		
		if(request.getParameter("template_type")!=null && !request.getParameter("template_type").toString().trim().equals("")){
			where+=" and template_type = ? ";
			whereParamList.add(request.getParameter("template_type"));
		}
		
		//分页处理
		int pageIndex=1;
		if(request.getParameter("pageIndex")!=null && !request.getParameter("pageIndex").toString().trim().equals("")){
			pageIndex=new Integer(request.getParameter("pageIndex")).intValue();
		}
		int pageSize=10;
		if(request.getParameter("pageSize")!=null && !request.getParameter("pageSize").toString().trim().equals("")){
			pageSize=new Integer(request.getParameter("pageSize")).intValue();
		}
		int start=0;
		if(pageIndex>1){
			start=(pageIndex-1)*pageSize;
		}
		whereParamList.add(start);
		whereParamList.add(pageSize);
		
		//排序参数 
		String sortField="id";
		String sortOrder="asc";
		if(request.getParameter("sortField")!=null && !request.getParameter("sortField").equals(""))
			sortField = request.getParameter("sortField");
		if(request.getParameter("sortOrder")!=null && !request.getParameter("sortOrder").equals(""))
			sortOrder = request.getParameter("sortOrder");
		
		//查询列表数据
		List dataList=this.getCommonService().getJdbcDao().querySql("select * from "+DBTable.template+" "+where+" order by "+sortField+" "+sortOrder+" limit ?,?", whereParamList.toArray());
		if(dataList!=null && dataList.size()>0){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			for(int i=0;i<dataList.size();i++){
				Map row=(Map)dataList.get(i);
				if(row.get("create_time")!=null) {
					Date date = (Date)row.get("create_time");
					row.put("create_time",sdf.format(date));
				}
				if(row.get("update_time")!=null) {
					Date date = (Date)row.get("update_time");
					row.put("update_time",sdf.format(date));
				}
				
				//查询模板所属的站点
				if(row.get("site_id")!=null) {
					int siteId=Integer.parseInt(row.get("site_id").toString());
					Map site=this.getCommonService().getJdbcDao().queryRow("select id,name from "+DBTable.site+" where id=? and del_flag=0 limit 0,1", new Object[] {siteId});
					if(site!=null) {
						row.put("site_name",site.get("name"));
					}
					
				}
				
			}
		}
		
		//查询总条数
		Map countRow=this.getCommonService().getJdbcDao().queryRow("select count(id) as count_num from "+DBTable.template+" "+where, whereParamList.subList(0, whereParamList.size()-2).toArray());
		int recordsTotal=0;
		if(countRow.get("count_num")!=null){
			recordsTotal=new Integer(countRow.get("count_num").toString()).intValue();
		}
		
		//拼装返回的数据
		data.put("data", dataList.toArray());
		data.put("itemsCount", recordsTotal);
		
		
		
		return WebUtil.resultString(data,request);
	}
	
	//更新发布状态
	@RequestMapping(value="/updatePublish",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String updatePublish(HttpServletRequest request){
		String num = "1".equals(request.getParameter("publish"))?"0":"1";
		this.getCommonService().getJdbcDao().updateSql("update "+DBTable.template+" set publish=? where id=?",new Object[]{num,request.getParameter("id")});
		Map result=new HashMap();
		result.put("result",1);
		result.put("msg", "操作成功");
		
		return WebUtil.resultString(result,request);
	}
	
	//扫描模板目录，检测模板
	@RequestMapping(value="/init",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String init(HttpServletRequest request){
		
		//扫描模板目录找到各模板目录
		Map templatesMap=new HashMap();
		String templatesPath=templateService.getTemplatesPath();
		if(templatesPath==null || templatesPath.equals("")) {
			Map result=new HashMap();
			result.put("result",0);
			result.put("msg", "模板目录未配置");
			return WebUtil.resultString(result,request);
		}
		
		
		File dir=new File(templatesPath);
		if(dir.exists() && dir.isDirectory()){
			//log.info("path: "+dir.getAbsolutePath());
			String[] files=dir.list();
			for(int i=0;i<files.length;i++){
				File templateDir=new File(templatesPath+"/"+files[i]);
				if(templateDir.exists() && templateDir.isDirectory()) {
					Map templateConfigData=templateService.getConfig(files[i]);
					if(templateConfigData!=null) {
						templateConfigData.put("path", files[i]);
						templatesMap.put(templateConfigData.get("code").toString(), templateConfigData);
					}
					
					
				}
			}
			files=null;
		}else {
			Map result=new HashMap();
			result.put("result",0);
			result.put("msg", "模板目录不存在");
			
			return WebUtil.resultString(result,request);
		}
		
		//循环现有的模板表数据，看是否存在不可用数据，有的话更新模板名称及类型字段
		List templateList=this.getCommonService().getJdbcDao().querySql("select * from "+DBTable.template+" where del_flag=0 limit 0,1000");
		if(templateList!=null) {
			for(int i=0;i<templateList.size();i++) {
				Map tmpTemplate=(Map)templateList.get(i);
				String code=tmpTemplate.get("code").toString();
				if(templatesMap.get(code)==null) {
					//设置为不可用状态
					this.getCommonService().getJdbcDao().updateSql("update "+DBTable.template+" set status=0 where id=?", new Object[] {tmpTemplate.get("id")});
				}
			}
		}
		
		int count=0;
		
		//循环读取配置文件，判断是否需要新增模板数据
		for(Object code : templatesMap.keySet()) {  	  
			Map tmpTemplate=this.getCommonService().getJdbcDao().queryRow("select id from "+DBTable.template+" where del_flag=0 and code=? limit 0,1", new Object[] {code});
			if(tmpTemplate==null) {
				Date timenow=new Date();
				Map newTemplate=(Map)templatesMap.get(code);
				Map record=new HashMap();
				record.put("name", newTemplate.get("name"));
				record.put("code", newTemplate.get("code"));
				record.put("template_place", 1);
				record.put("template_type", newTemplate.get("type"));
				record.put("template_path", newTemplate.get("path"));
				
				/*if(newTemplate.get("allowEdit")!=null && newTemplate.get("allowEdit").toString().equals("true")) {
					record.put("allow_edit", 1);
				}else {
					record.put("allow_edit", 0);
				}*/
				
				
				record.put("publish", 1);
				record.put("status", 1);
				record.put("create_time", timenow);
				record.put("update_time", timenow);
				this.getCommonService().getJdbcDao().addObj(DBTable.template, record);
			}
			count++;
		} 
		
		
		Map result=new HashMap();
		result.put("result",1);
		result.put("msg", "扫描完成，模板目录下共有"+count+"套模板文件");
		
		return WebUtil.resultString(result,request);
	}
	
	
	
}
